package com.zan.zanchat.common.common.event.listener;

import com.zan.zanchat.common.common.event.UserOnlineEvent;
import com.zan.zanchat.common.user.dao.UserDao;
import com.zan.zanchat.common.user.domain.entity.User;
import com.zan.zanchat.common.user.domain.enums.UserActiveStatusEnum;
import com.zan.zanchat.common.user.service.IpService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @Author Zan
 * @Create 2024/3/17 19:57
 * @Description :
 */
@Component
public class UserOnlineListener {

    @Resource
    private UserDao userDao;

    @Resource
    private IpService ipService;

    /**
     * 注意：这里使用了@TransactionalEventListener，这是事务的，因此如果前面没有事务，那么就不会生效，也就不会发生事件
     * 如果一定要使用@TransactionalEventListener，那么就需要配置一下参数fallbackExecution = true
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserOnlineEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void saveDB(UserOnlineEvent event) {
        User user = event.getUser();
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setLastOptTime(user.getLastOptTime());
        updateUser.setIpInfo(user.getIpInfo());
        updateUser.setActiveStatus(UserActiveStatusEnum.ONLINE.getStatus());
        userDao.updateById(updateUser);
        // 用户ip详情的解析
        ipService.refreshIpDetailAsync(user.getId());
    }
}
